package com.tangjinghao.monitor.custom;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatButton;

/**
 * @Author 唐靖豪
 * @Date 2022/7/12 22:52
 * @Email 762795632@qq.com
 * @Description
 */

public class MyButton extends AppCompatButton {
    long lastTimeStamp;//记录按下的时间
    boolean isPress;//判断是否在按压
    ClickListener listener;
    Thread thread;

    public MyButton(Context context) {
        super(context);
    }

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //按下时设置select为true 变换selector状态
                setSelected(true);
                isPress = true;
                lastTimeStamp = System.currentTimeMillis();
                //一直执行
                thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (isPress) {
                            //判断按压时间超过300毫秒视为长按
                            if ((System.currentTimeMillis() - lastTimeStamp) > 300) {
                                listener.onClick();
                                try {
                                    Thread.sleep(10);//间隔50毫秒这里决定长按时 执行点击方法的频率
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
                thread.start();
                break;
            case MotionEvent.ACTION_UP:
                //抬起设置select为false
                setSelected(false);
                thread.interrupt();
                //判断按压时间小于300毫秒视为单击
                if ((System.currentTimeMillis() - lastTimeStamp) <= 300) {
                    //触发单击事件
                    listener.onClick();
                }
                isPress = false;
                break;
        }
        return true;
    }

    public void setClickListener(ClickListener listener) {
        this.listener = listener;
    }

    public interface ClickListener {
        void onClick();
    }



}
